<template>
	<view>
		<view class="search-input" id="search-input">
			<!-- 填充 -->
			<view :style="`height:${app.globalData.STATUS_BAR_HEIGHT}px`"></view>
			<!-- <up-search  @click="toSearchPage()" shape="square"
				placeholder="首拼/名称/编号/条码" :clearabled="true" :showAction="false" bgColor="#4e77cf"
				searchIconColor="#dedede" placeholderColor="#DEDEDE" color="#ffffff" height="64rpx"
				disabled></up-search> -->

			<view style="display: flex;">
				<up-icon name="arrow-left" color="#DEDEDE" size="48rpx"
					@click="uni.navigateBack()"></up-icon>
				<up-search style="margin-left: 10rpx;" @click="toSearchPage()" shape="square"
					placeholder="首拼/名称/编号/条码" :clearabled="true" :showAction="false"
					bgColor="#4e77cf" searchIconColor="#dedede" placeholderColor="#DEDEDE"
					color="#ffffff" height="64rpx" disabled></up-search>
				<up-icon style="margin-left: 10rpx;" name="scan" color="#DEDEDE"
					size="54rpx"></up-icon>
				<!-- <up-icon style="margin-left: 10rpx;" name="arrow-down" color="#DEDEDE"
					size="48rpx"></up-icon> -->
			</view>
		</view>
		<!-- 填充 -->
		<view :style="{height:catagoryViewPaddingTop+'px'}"></view>
		<view class="category-view" :style="{height:catagoryViewHeight+'px'}">
			<scroll-view class="category-left" scroll-y>
				<!-- <view @click="itemLeftClick(index)" v-for="index of 20"
					:class="index==selectLeftIndex?'category-left-item-select':''"
					class="category-left-item">
					有品{{index}}
				</view> -->
				<view @click="itemLeftClick(index)" v-for="(item,index) in brands"
					:class="index==selectLeftIndex?'category-left-item-select':''"
					class="category-left-item">
					<text>{{item.brand}}</text>
					<text v-if="car[item.brand]" style="display: inline-flex;
								  margin-left: 10rpx;
								  width: 28rpx;  /* 直径尺寸 */
								  height: 28rpx; /* 必须与宽度相等 */
								  background-color: #FF5722; /* 背景色 */
								  border-radius: 50%; /* 关键属性 */
								  justify-content: center;
								  align-items: center;
								  color: #FFFFFF; /* 文字颜色 */">{{car[item.brand].length}}</text>
				</view>
			</scroll-view>
			<scroll-view style="background-color: #ffffff;" class="category-right" scroll-y>
				<view style="padding: 20rpx;border-bottom: 1px solid #dcdfe6;"
					v-for="(item,index) in dataList" @click="selectRightIndex = index">
					<view style="font-weight: bold;">{{item.pname}}</view>
					<view style="color: #75747c;position: relative;">
						<!-- <text>0瓶</text>
						<text style="margin-left: 20rpx;">1箱=12瓶</text> -->
						<text>&nbsp</text>
						<text
							style="position: absolute;right: 0;">{{ item.bigunit?`￥${item.bigprice}\/${item.bigunit}`:`￥${item.smallprice}\/${item.smallunit}` }}</text>
					</view>
					<view v-show="index==selectRightIndex">
						<view style="display: flex;margin-top: 20rpx;" v-if="item.bigunit"
							v-for="(u_item,u_index) in item.itemList">
							<button v-if="u_item.saletype!='常规销售'" @click="showPopup(u_item)"
								style="display: flex;align-items: center; border:2rpx solid #000;border-radius: 50rpx;padding: 0 20rpx;margin-left: 0;background-color: #f3f2f7;"
								size="mini">
								<text
									style="padding: 0 20rpx;border-radius: 50%;background-color:#e36a4e ;color:#fff">{{u_item.saletype.slice(-1)}}</text>
								<text>{{`￥${u_item.unitprice}\/${u_item.unit}`}}</text>
								<up-icon name="arrow-down-fill"
									style="margin-left: 10rpx;"></up-icon>
							</button>
							<button v-else
								style="display: flex;align-items: center; border:2rpx solid #000;border-radius: 50rpx;padding: 0 20rpx;margin-left: 0;background-color: #f3f2f7;"
								size="mini">
								<text>{{`￥${u_item.unitprice}\/${u_item.unit}`}}</text>
							</button>
							<up-number-box v-model="u_item.number" buttonSize="25" buttonWidth="25"
								min="0"
								@change="countChange($event,brands[selectLeftIndex].brand,index)"
								integer></up-number-box>
						</view>
					</view>
				</view>
				<!-- 填充 -->
				<!-- <view style="height: 10rpx;"></view> -->
			</scroll-view>
		</view>

		<!-- 弹出层 -->
		<up-popup :show="popupShow" :round="10" mode="bottom" @close="popupClose()"
			:safeAreaInsetTop="true" closeable>
			<view style="padding: 20rpx;">
				<view style="font-weight: bold;font-size: 34rpx;">
					{{dataList[selectRightIndex].pname}}
				</view>
				<view style="margin-top: 20rpx;">
					<view style="color:#9c9aa5">业务属性</view>
					<view style="display: flex;width: 100%;margin-top: 10rpx;">
						<up-button @click="b_type = '0元赠'"
							:customStyle="{height:'64rpx',color:'#000'}" color="#d8d8d8" text="0元赠"
							:plain="b_type!='0元赠'"></up-button>
						<up-button @click="b_type = '兑奖'"
							:customStyle="{height:'64rpx',marginLeft:'10rpx',color:'#000'}"
							color="#d8d8d8" text="兑奖" :plain="b_type!='兑奖'"></up-button>
						<up-button @click="b_type = '销售换货'"
							:customStyle="{height:'64rpx',marginLeft:'10rpx',color:'#000'}"
							color="#d8d8d8" text="销售换货" :plain="b_type!='销售换货'"></up-button>
						<!-- <up-button
							:customStyle="{height:'64rpx',marginLeft:'10rpx',color:'#ebf7fd'}"
							color="#d8d8d8" text="销售换货" :plain="type!=2"></up-button> -->
					</view>
				</view>
				<view style="margin-top: 20rpx;">
					<view style="color:#9c9aa5">单位</view>
					<view style="display: flex;width: 100%;margin-top: 10rpx;">
						<up-button v-for="(item,index) in dataList[selectRightIndex].unitList"
							@click="u_type = item"
							:customStyle="{height:'64rpx',color:'#000',marginLeft:index!=0?'10rpx':'0'}"
							color="#d8d8d8" :text="item" :plain="u_type!=item"></up-button>
						<!-- <up-button @click="u_type = '瓶'"
							:customStyle="{height:'64rpx',marginLeft:'10rpx',color:'#000'}"
							color="#d8d8d8" text="瓶" :plain="u_type!='瓶'"></up-button> -->
					</view>
				</view>
				<view style="margin-top: 20rpx;" v-show="b_type == '销售换货' || b_type == '兑奖'">
					<view style="color:#9c9aa5">单价</view>
					<view style="display: flex;width: 100%;margin-top: 10rpx;">
						<up-input placeholder="" type="number" v-model="unit_price">
							<template #prefix>
								<up-text text="￥" margin="0 3px 0 0" type="tips"></up-text>
							</template>
						</up-input>
					</view>
				</view>
				<view style="margin-top: 20rpx;">
					<up-button type="primary"
						@click="sureGive(selectLeftIndex, selectRightIndex)">确定</up-button>
				</view>
			</view>
		</up-popup>


		<view class="bottom-box" id="bottom-box">
			<view style="padding: 20rpx;width: 160rpx;margin-left: auto;">
				<up-button type="primary"
					@click="submitSelect()">添加({{carProductCount}})</up-button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref, reactive, watch, computed, nextTick, getCurrentInstance } from 'vue'
	import { onReady, onLoad } from "@dcloudio/uni-app"
	const app = getApp()

	const catagoryViewHeight = ref(0)
	const catagoryViewPaddingTop = ref(0)
	onReady(() => {
		//.box获取class为box的元素，如果使用的id= 'box' 则使用'#box'
		uni.createSelectorQuery().select('#search-input').boundingClientRect(s_data => {
			uni.createSelectorQuery().select('#bottom-box').boundingClientRect(
				b_data => {
					catagoryViewPaddingTop.value = s_data.height
					catagoryViewHeight.value = app.globalData.SCREEN_HEIGHT -
						s_data.height - b_data.height
				}).exec()
		}).exec()
	})

	onLoad(async () => {
		// 可能上个页面有car传进来
		const eventChannel = getCurrentInstance().proxy.getOpenerEventChannel();
		eventChannel.on('setCar', (data) => {
			car.value = data


		})

		const res = await app.globalData.http.get("/wms/product/listbrand")
		brands.value = res.rows
		if (brands.value.length > 0) {
			itemLeftClick(0)
		}
	})

	const itemLeftClick = async (index) => {
		// 选中左边
		selectLeftIndex.value = index

		// 请求右边
		const params = { brand: brands.value[index].brand }
		const url = app.globalData.buildUrl("/wms/product/listsale", params)
		const res = await app.globalData.http.get(url)


		const car2list = Object.values(car.value).flat()
		res.rows.forEach((item) => {
			// 如果item.pid与car2list中某条数据的pid相同，则用某条数据的itemList覆盖item.itemList
			const matchedItem = car2list.find(carItem => carItem.pid === item.pid)
			if (matchedItem && matchedItem.itemList) {
				item.itemList = matchedItem.itemList
			}
		})
		dataList.value = res.rows
	}
	const toSearchPage = (index) => {
		uni.navigateTo({
			url: '/pages/searchPage'
		})
	}



	// 弹窗相关
	const popupShow = ref(false);
	// 业务类型
	const b_type = ref("0元赠")
	// 单位
	const u_type = ref("箱")
	// 单价
	const unit_price = ref(null)

	const resetPopup = () => {
		b_type.value = "0元赠"
		u_type.value = "箱"
		unit_price.value = null
	}

	const showPopup = async (u_item) => {
		popupShow.value = true
	}
	const popupClose = () => {
		resetPopup()
		popupShow.value = false
	}

	// 确定赠送相关信息
	const sureGive = async (selectLeftIndex, selectRightIndex) => {
		popupShow.value = false
		await nextTick();
		dataList.value[selectRightIndex].itemList.forEach((item, index) => {
			if (item.saletype != '常规销售') {
				item.unit = u_type.value
				item.saletype = b_type.value
				item.unitprice = unit_price.value ? unit_price.value : 0
			}
		})
		resetPopup()
		// 修改car中的数据
		const brandId = brands.value[selectLeftIndex].brand

		// 确保该品牌的数组存在
		if (car.value[brandId]) {
			const productIndex = car.value[brandId].findIndex(cartItem => cartItem.pid ===
				dataList.value[selectRightIndex].pid);
			if (productIndex !== -1) { // 如果购物车中已存在此商品，更新它
				car.value[brandId][productIndex] = dataList.value[selectRightIndex];
			}
			console.log(car.value)
		}

	}

	// 左边选中
	const selectLeftIndex = ref(0)
	// 商品品牌，每一个商品品牌对应一个dataList
	const brands = ref([])

	// dataList中每一条记录都是一个商品，商品对象有个itemList数组属性，
	// itemList中每一条记录代表此商品的不同unit且每一条记录中都有一个number属性，是用户选择的数量)
	const dataList = ref([])
	// 右边选中
	const selectRightIndex = ref(0)
	// 购物车
	const car = ref({
		/*"一担粮": [
			{ pid: 10, pname: "壹号白酒", itemList: [] },
			{ pid: 11, pname: "花酒", itemList: [] },
		],
		"雪花": [
			{ pid: 121, pname: "天涯", itemList: [] },
		]*/
	})

	// 计算购物车中有多少种不同的商品
	const carProductCount = computed(() => {
		return Object.values(car.value).reduce((total, brandProducts) => {
			return total + brandProducts.length;
		}, 0);
	});


	// itemList数量变化 brandId为中文字符串如"一担粮",其实每一个商品中有一个brand字段
	const countChange = async (e, brandId, p_index, u_index) => {
		// 异步更新问题：Vue的响应式更新可能存在时机差异
		// 当我们使用p_index去访问对象的时候，极有可能双向绑定的itemList的number还未修改完毕
		// 此处可以优化，使用e.target.value来完成逻辑
		await nextTick();
		// 1. 检查当前商品的所有itemList的number是否都为0
		const allItemsZero = dataList.value[p_index].itemList.every(item => {
			// console.log('item.number:', item.number, 'type:', typeof item.number);
			return item.number === 0
		});
		if (allItemsZero) { // 2. 如果所有number都为0，从购物车中移除此商品
			if (car.value[brandId]) { // 如果所有number都为0，说明此前不是都为0，那么car中一定会有brandId
				const productIndex = car.value[brandId].findIndex(cartItem => cartItem
					.pid === dataList.value[p_index].pid);
				if (productIndex !== -1) { // 说明找到了
					car.value[brandId].splice(productIndex, 1);
					// 如果该品牌下没有商品了，删除整个品牌
					if (car.value[brandId].length === 0) {
						delete car.value[brandId];
					}
				}
			}
		} else { // 3. 如果不为0，更新购物车中对应的商品
			const selectedItems = dataList.value[p_index].itemList;
			// 确保该品牌的数组存在
			if (!car.value[brandId]) {
				car.value[brandId] = [];
			}

			// 查找该品牌下是否已存在此商品
			const productIndex = car.value[brandId].findIndex(cartItem => cartItem.pid ===
				dataList
				.value[p_index].pid);
			if (productIndex !== -1) { // 如果购物车中已存在此商品，更新它
				car.value[brandId][productIndex] = dataList.value[p_index];
			} else { // 如果购物车中不存在此商品，添加它
				car.value[brandId].push({ ...dataList.value[p_index] });
			}
		}
		console.log(car.value)
	}

	// 提交用户选中
	const submitSelect = () => {
		let pages = getCurrentPages()
		let prevPage = pages[pages.length - 2]; //上一页页面实例
		prevPage._.exposed.setCar(car.value)
		uni.navigateBack()
	}
</script>

<style lang="scss" scoped>
	.search-input {
		background-color: #2757c5;
		width: auto;
		padding: 30rpx;
		position: fixed;
		left: 0;
		right: 0;
		z-index: 999;
	}

	.category-view {
		display: flex;

		.category-left {
			height: 100%;
			width: 200rpx;
			display: flex;
			flex-direction: column;
			background-color: #f3f2f7;
			color: #888693;

			.category-left-item {
				line-height: 2.5;
				text-align: center;

			}

			.category-left-item-select {
				background-color: #ffffff;
				color: #000;
			}

			// .category-left-item:last-of-type {
			// 	padding-bottom: 30rpx !important;
			// }
		}

		.category-right {
			height: 100%;
			flex: 1;
			background-color: #f6f6f6;

		}
	}

	.bottom-box {
		background-color: #ffffff;
		// height: 100rpx;
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		z-index: 998;
		box-sizing: content-box;
		border-top: 1px solid #dedede;
		padding-bottom: env(safe-area-inset-bottom);
	}
</style>